import storage from '@/utils/storage.js'

import { REDIRECTURL, ROUTESTACK } from '@/store/constant.js'


const state = {
  // 成功登录之后重定向路由路径
  redirectURL: storage.get(REDIRECTURL, ''),
  // 路由栈堆
  // 小程序
  // #ifndef H5
  routeStack: storage.get(ROUTESTACK, []),
  // #endif

  // H5
  // #ifdef H5
  routeStack: storage.sessionGet(ROUTESTACK, [])
  // #endif
}

const mutations = {
  // 设置登录之后重定向路由路径
  setRedirectURL: (state, path) => {
    state.redirectURL = path
    storage.set(REDIRECTURL, path)
  },
  // 删除登录之后重定向路由路径
  removeRedirectURL: (state) => {
    storage.remove(REDIRECTURL)
    state.redirectURL = ''
  },
  // 设置页面路由栈堆-->TODO:setRedirectURL可能要废弃
  setRouteStack: (state, path) => {
    const isHas = state.routeStack.includes(path)
    // 路由栈堆存在即不存进去
    if (!isHas) {
      state.routeStack.push(path)
      // #ifndef H5
      storage.set(ROUTESTACK, state.routeStack)
      // #endif

      // #ifdef H5
      storage.sessionSet(ROUTESTACK, state.routeStack)
      // #endif
    }
  },
  // 删除路由栈某个路由
  removeRouteStack: (state, path) => {
    for (let i = 0, length = state.routeStack.length;  i < length; i++) {
      const routeItem = state.routeStack[i]
      if (routeItem === path) {
        state.routeStack.splice(i, 1)
        // #ifndef H5
        storage.set(ROUTESTACK, state.routeStack)
        // #endif

        // #ifdef H5
        storage.sessionSet(ROUTESTACK, state.routeStack)
        // #endif
        return false
      }
    }
  },
  // 清空路由栈
  clearRouteStack: (state) => {
    state.routeStack = []
    // #ifndef H5
    storage.remove(ROUTESTACK)
    // #endif

    // #ifdef H5
    storage.sessionRemove(ROUTESTACK)
    // #endif
  }
}

const getters = {
  redirectURL: (state) => state.redirectURL,
  routeStack: (state) => state.routeStack
}

export default {
  state,
  mutations,
  getters
}